<template>
  <div class="">
    <div class="ja-container" id="jobapp" v-if="isVip">
      <!-- <p class="prompt-text" style="margin: 5px 0;">初审未通过后可以再次编辑提交，终审未通过后不可再次编辑修改</p> -->
      <div class="ja-btns">
        <!-- <div class="" style="margin-bottom: 8px;">
          <el-button type="success" plain icon="el-icon-download" @click="downloadFile()">汇总表Excel模板下载</el-button>
        </div> -->

        <el-button type="success" icon="el-icon-plus" @click="add()" style="font-size: 14px;padding: 8px;">新增申请</el-button>
        <!-- <el-button type="success" plain icon="el-icon-download" style="font-size: 14px;padding: 8px;" @click="downloadFile()">汇总模板</el-button> -->
        <!-- <el-button type="success" plain icon="el-icon-download" style="font-size: 14px;padding: 8px;" @click="downloadPersonFile()">个人模板</el-button> -->
      </div>
      <el-tabs @tab-click="all" v-model="activeName">
        <el-tab-pane label="全部" >
          <el-dropdown slot="label" @command="changeCondition">
            <span class="el-dropdown-link">
              {{condition}}
              <i class="el-icon-arrow-down ml-2"></i>
            </span>
            <el-dropdown-menu slot="dropdown" >
              <el-dropdown-item command="全部">全部</el-dropdown-item>
              <el-dropdown-item command="未提交">未提交</el-dropdown-item>
              <el-dropdown-item command="待审核">待审核</el-dropdown-item>
              <el-dropdown-item command="已审核">已审核</el-dropdown-item>
              <el-dropdown-item command="已通过">审核成功</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-tab-pane>
        <el-tab-pane label="未通过">
          <span slot="label">
            未通过
            <!-- <el-badge :value="200" :max="99" class="item"></el-badge> -->
          </span>
        </el-tab-pane>
      </el-tabs>
      <!-- <jobapp-list ref="list" :offset.sync="offset" :limit.sync="limit" :sort.sync="sort" :order.sync="order"
      :data="data" :total="total" @selected="selected"></jobapp-list> -->
      <jobapp-group ref="group" :data="data" @selected="selected" @submit-all="saveAll" @delete-row-success="refresh"></jobapp-group>
    </div>
    <div class="flex-column-center promp-msg" style="height: 500px;" v-if="!isVip">
      <img src="static/gongnengtishi.png" alt="">
      <h2>无操作权限</h2>
      <span v-if="noVipStatus === 'NOVIP'">很抱歉！只有会员才可进行此操作，请先申请为会员！</span>
      <span v-if="noVipStatus === 'DISABLED'">会员已被禁用，暂时无法进行相关操作</span>
      <span v-if="noVipStatus === 'WAIT'">会员为待缴费状态，请及时缴费</span>
    </div>
    <el-dialog
      @close="dialogClose"
      :visible.sync="allSub"
      width="45%"
      id="job-dialog-ec"

      center>
      <div class="flex-row">
        <div class="material-textfield green form-left" style="padding-right: 20px" :class="{'validate-err': errors.has('contactsName')}">
          <input type="text" required v-model="companyinfo.contactsName" v-validate="'required'" name="contactsName"/>
          <label data-content="职称申报联系人*"></label>
        </div><!--
      --><div class="material-textfield green form-right" style="padding-left: 20px" :class="{'validate-err': errors.has('contactsPhone')}">
          <input type="text" required v-model="companyinfo.contactsPhone" v-validate="'required|fax'" name="contactsPhone"/>
          <label data-content="联系方式*"></label>
        </div>
      </div>

      <div class="flex-row ">
        <div class="material-textfield green form-left" style="padding-right: 20px" :class="{'validate-err': errors.has('department')}">
          <input type="text" required v-model="companyinfo.department"  v-validate="'required'" name="department"/>
          <label data-content="工作部门*"></label>
        </div>
      </div>

      <!-- 上传企业附件 -->
      <div class="flex-row vip-upload" :class="{'validate-err': !(companyinfo.attachment && companyinfo.attachment.length > 0) }">
        <label data-content="上传附件" class="ewai" >上传附件</label>
        <!-- attachment 附件资料-->
        <el-upload
          class=""
          ref="upload"
          action="/mscs/user/fileUpload"
          :multiple="true"
          :headers="{authorization: authorization}"
          :on-remove="handleRemove"
          :limit="1"
          :file-list="fileList"
          :on-success="uploadSuccess"
          accept="image/*, .rar, .zip,.doc, .docx, .pdf, .jpg, .xls,.txt,.xlm, .xls"
          :on-error="uploadError"
          :before-upload="uploadBefore"
          :on-exceed="onExceed"
          >
          <el-button slot="trigger" class="width-200">选取文件</el-button>
          <!-- <span slot="tip" class="el-upload__tip">上传企业附件，不超过15M</span> -->
        </el-upload>
      </div>
      <p>说明：1. 此为企业申请人汇总表盖章后的照片或扫描件；</p>
      <p style="padding-left: 45px;">2.只能上传一个附件，不超过15M</p>

      <div class="tc">
        <el-button type="success width-200"  round @click="submitAll()">上报</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import eventBus from '../plugins/eventbus.js'
import $ from 'jquery'

import JobappGroup from './jobappform/JobappGroup'
// import JobappList from './jobappform/JobappList'

  export default {
    components: {
      // JobappList,
      JobappGroup
    },
    title: '初级职称申请',
    name: 'job-app',
    data () {
      return {
        activeName: '0',
        offset: 1,
        limit: 15,
        sort: '',
        order: '',
        currentPage: 1,
        data: [],
        total: 0,
        index: 0,
        allSub: false,
        condition: '全部',
        companyinfo: {
          attachment: '',
          department: '',
          contactsName: '',
          contactsPhone: ''
        },
        fileList: [] // 企业附件
      }
    },
    mounted () {
      this.all({index: this.index})
      if (!this.isVip) {
        this.getUserType()
      }
      this.activated()
      this.getData()
    },
    methods: {
      add () {
        if (this.$store.state.isJob) {
          this.$router.push({path: '/jobform'})
        } else {
          this.$alert(new Date().getFullYear() + '年的初级职称评审申报工作已结束，无法新增。', {
            confirmButtonText: '确定',
          })
        }
      },
      all(tabvm) {
        if (tabvm.index === '1') {
          this.$refs.group.modifyFilter('未通过')
        } else if (tabvm.index === '0') {
          this.$refs.group.modifyFilter(this.condition)
        }
      },
      getData (params) {
        // debugger
        axios.post('/mscs/review/findMptrInfo', this.$paramsConvert({userId: this.$store.state.user.user.user.userId})).then((res) => {
          this.data = res.data.data
          // this.total = res.data.data.total
        }).catch((error) => {
          this.$catchError(error)
        })
      },
      // 选择某一行
      selected (row) {
        this.$router.push({name: 'jobform', params: row})
      },
      // 保存完成后刷新使用
      activated(){
          //根据key名获取传递回来的参数，data就是map
          eventBus.$on('confirm-success', function(data){
            this.all({index: 0})
          }.bind(this));
      },
      refresh () {
        this.getData()
      },
      saveAll (data) {
        if (data) { // 批量保存的修改
          this.companyinfo.department = data.department
          this.companyinfo.contactsName = data.contactsName
          this.companyinfo.contactsPhone = data.contactsPhone
          this.fileList = JSON.parse(data.attachment)
          this.companyinfo.attachment = JSON.parse(data.attachment)
          // 后台需要
          this.companyinfo.companyName = data.companyName
          this.companyinfo.ctime = data.ctime
          this.companyinfo.reviewEnterpriseId = data.reviewEnterpriseId

          this.companyinfo.cityName = data.cityName
          this.companyinfo.cityCode = data.cityCode
          // 将附件也默认上
        } else { // 新增加的人员批量修改
          let companyinfo = this.$lsget('companyinfo')
          if (companyinfo) {
            this.companyinfo.department = companyinfo.department ? companyinfo.department : ''
            this.companyinfo.contactsName = companyinfo.contactsName ? companyinfo.contactsName : ''
            this.companyinfo.contactsPhone = companyinfo.contactsPhone ? companyinfo.contactsPhone : ''
            this.companyinfo.attachment = ''
            this.fileList = []
          } else {
            this.companyinfo.department = ''
            this.companyinfo.contactsName = ''
            this.companyinfo.contactsPhone = ''
            this.companyinfo.attachment = ''
            this.fileList = []
          }
        }

        this.allSub = true
      },
      submitAll () {
        this.$validator.validate().then(result => {
          if (result) {
            if (!(this.companyinfo.attachment.length > 0)) {
              return
            }
            // 提交
            let obj = Object.assign({}, this.companyinfo, {userId: this.$store.state.user.user.user.userId})
            obj.attachment = JSON.stringify(obj.attachment)
            axios.post('/mscs/review/modSaveSubmitStatus', obj).then((res) => {
              if (res.data.code === 1) {
                this.$message({
                  showClose: true,
                  message: '提交成功',
                  type: 'success'
                })

                // 奖填写的内容缓存起来，后来自动填写
                this.$lsput('companyinfo', this.companyinfo)
                this.getData()
              } else {
                this.$codeError(res)
              }
            }).catch((error) => {
              this.$catchError(error)
            })
            this.allSub = false
          }
        })
      },
      getUserType () {
        axios.post('/mscs/user/findUserType', this.$paramsConvert({userId: this.$store.state.user.user.user.userId})).then((res) => {
          if (res.data.code === 1) {
            this.$store.commit('upUserType', {userType: res.data.data.userType})
            if (res.data.data.memberStatus) {
              this.$store.commit('upMemberStatus', res.data.data.memberStatus)
            }
            if (res.data.data.paymentStatus) {
              this.$store.commit('upPaymentStatus', res.data.data.paymentStatus)
            }
          }
        })
      },
      // 文件上传相关
      handleRemove (file, fileList) {
        this.companyinfo.attachment = []
        fileList.forEach((item, index) => {
          if (item.response) {
            this.companyinfo.attachment[index] = {name: item.name, url: item.response.data, id: index+1}
          } else if (!item.size) { // 回传数据
            this.companyinfo.attachment[index] = {name: item.name, url: item.url, id: item.id}
          }
        })
      },
      uploadSuccess (res, file, fileList) {
        if (res.code === 1) {
          this.companyinfo.attachment = []
          fileList.forEach((item, index) => {
            if (item.response) {
              this.companyinfo.attachment[index] = {name: item.name, url: item.response.data, id: index+1}
            } else if (!item.size) { // 回传数据
              this.companyinfo.attachment[index] = {name: item.name, url: item.url, id: item.id}
            }
          })
          this.$message({
            message: '文件上传成功',
            type: 'success'
          })
        }
      },
      uploadError (err, file, fileList) {
        if (err.status === 401) {
          this.$openLogin()
        } else {
          this.$message({
            showClose: true,
            message: '文件上传失败',
            type: 'error'
          })
        }
      },
      uploadBefore (file) {
        let type = file.name.split('.')[file.name.split('.').length-1].toLowerCase()
        if (file.size/1024/1024 > 15) {
          this.$message({
            showClose: true,
            message: '文件过大，无法上传',
            type: 'error'
          })
          return false
        }
        if (type === 'zip' || type === 'doc' || type === 'docx' || type === 'pdf' || type === 'jpg' || type === 'xls'
            || type === 'png' || type === 'xlsx' || type === 'jpeg') {
          return true
        } else {
          this.$message({
            showClose: true,
            message: '文件类型不匹配',
            type: 'error'
          })
          return false
        }
      },
      onExceed (files, fileList) {
        this.$message({
          showClose: true,
          message: '只能上传一个附件',
          type: 'error'
        })
      },
      changeCondition (str) {
        this.activeName = '0'
        this.condition = str
        this.$refs.group.modifyFilter(str)
      },
      // 对话框关闭
      dialogClose () {
        this.companyinfo = {
          attachment: '',
          department: '',
          contactsName: '',
          contactsPhone: '',
        }
      },
      downloadFile () {
        var $form = $('<form method="GET"></form>');
        $form.attr('action', 'http://cdn.i-tudou.com/document/Summary-table.doc')
        $form.appendTo($('body'));
        $form.submit();
        // window.open('http://cdn.i-tudou.com/document/Summary-table.doc')
      },
      downloadPersonFile () {
        var $form = $('<form method="GET"></form>');
        $form.attr('action', 'http://cdn.i-tudou.com/document/Application-form-of-title.zip')
        $form.appendTo($('body'));
        $form.submit();
      }
    },
    computed: {
      isVip () {
        return this.$store.state.user.user &&
        (this.$store.state.user.user.user.userType === 'MEMBER' || this.$store.state.user.user.user.userType === 'CMEMBER') &&
        this.$store.state.user.user.memberStatus === "NORMAL" &&
        this.$store.state.user.user.paymentStatus === "ALREADY"
      },
      noVipStatus () {
        if (!(this.$store.state.user.user && (this.$store.state.user.user.user.userType === 'MEMBER' || this.$store.state.user.user.user.userType === 'CMEMBER'))) {
          return 'NOVIP'
        }
        if (!(this.$store.state.user.user.memberStatus === "NORMAL")) {
          return 'DISABLED'
        }
        if (!(this.$store.state.user.user.paymentStatus === "ALREADY")) {
          return 'WAIT'
        }
      },
      authorization () {
        return this.$store.state.user.token
      }
    },
    watch: {
      'offset' (val) {
        this.all({index: this.index})
      },
      'limit' (val) {
        this.all({index: this.index})
      }
    },

  }
</script>
<style>
  .ja-container {
    padding-top: 25px;
    position: relative;
  }
  .ja-container .el-tabs__header {
    margin: 0;
  }
  .ja-container .el-tabs__nav-wrap::after {
    background-color: #94C05A;
    height: 1px;
  }
  .ja-container .el-tabs__item{
    font-size: 16px;
    width: 100px;
    text-align: center;
    padding-left: 0;
    padding-right: 0;
  }
  .ja-container .el-tabs__active-bar {
    height: 0;
    background-color: #94C05A;
    border-bottom: 0px solid transparent;
    width: 100px;
  }
  .ja-container .el-tabs__item.is-active {
    color: #94C05A;
    border-bottom: 3px solid #94C05A;
    font-weight: bold;
  }
  .ja-container .el-table th {
    /* background-color: #E4EED8; */
    color: #666;
  }
  .ja-container .el-table td, .el-table th.is-leaf {
    border-bottom: 1px solid #E0E6D8;
  }
  .ja-container .el-table_4_column_28 {
    border-left: 3px solid transparent;
  }
  .ja-container .current-row {
    box-shadow:  0px 0px 20px #94C05A;
  }
  .ja-container .el-table__row td {
    background-color: #F3F9EB;
  }
  .ja-container .current-row .el-table_4_column_28 {
    border-left: 3px solid #94C05A;
  }
  .ja-container .el-table--enable-row-hover .el-table__body tr:hover {
    color: #000;
    box-shadow:  0px 0px 20px #94C05A;
  }
  .ja-container .el-table--enable-row-hover .el-table__body tr:hover>td {
    background-color: #FFFFFF;
  }
  .ja-container .ja-btns {
    z-index: 1;
    position: absolute;
    right: 0;
    /* top: 0; */
  }
  #job-dialog-ec .el-dialog {
    border-radius: 10px;
  }
  #job-dialog-ec .el-dialog__body {
    padding: 40px;
  }
  /* #job-dialog-ec .material-textfield label::after {
    top: -2px;
  } */
  #jobapp .el-dropdown {
    font-size: 16px;
  }
  #jobapp .el-badge {
    top: 4px;
    left: 8px;
  }

  .ja-container .el-tabs__item .el-badge__content {
    background-color: #e0e0e0;
    color: #666;
  }
  .ja-container .el-tabs__item.is-active .el-badge__content {
    background-color: #94C05A;
    color: #FFFFFF;
  }
  .ja-container .el-dropdown-menu__item {
    font-size: 16px;
  }
  .ja-container .el-dropdown-menu__item:focus, .el-dropdown-menu__item:not(.is-disabled):hover {
    background-color: transparent;
    color: #94C05A;
  }
  .ja-container .el-tabs__item.is-active .el-dropdown {
    color: #94C05A;
  }
  </style>
